<template>
  <div :class="{'mobile-help-create mobile-create':showMobilePage}" class="help-create">
    <div :class="{'mobile-margin':showMobilePage}" class="create-head">
      <div class="back" @click="toHelpList">&lt;</div>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ name: 'help', query: { model: 'newRead' } }">帮助中心</el-breadcrumb-item>
        <el-breadcrumb-item>{{ title }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div :class="{'mobile-margin':showMobilePage}" class="create-box">
      <Title :title="title" :style="showMobilePage?'padding:20px 0':'padding:32px 0'"/>
      <el-form ref="helpForm" :model="helpForm" :rules="helpRules" :label-position="showMobilePage?'left':'right'" class="lineHeight32" label-width="70px">
        <el-form-item label="标题" prop="title">
          <el-input v-model.trim="helpForm.title" name="title" type="text" placeholder="请输入标题，不超过200字" size="small" maxlength="200" class="width240" />
        </el-form-item>
        <el-row>
          <el-col :span="4" :xs="24">
            <el-form-item label="模块" prop="model">
              <el-select
                v-model="helpForm.model"
                placeholder="请选择模块"
                size="small"
                class="width240">
                <el-option
                  v-for="item in getSelectModelOptions()"
                  :key="item.name"
                  :label="item.label"
                  :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="20" :xs="24">
            <el-form-item :label-width="showMobilePage?'':'100px'" label="封面图片">
              <div class="width240">
                <upAttachment
                  ref="uploadImg"
                  :hide-confirm="true"
                  :limit-file-size="10"
                  :limit="10"
                  :file-type="'jpg|png|gif'"
                  :file-list="helpForm.cover"
                  import-api="/common/file/upload"
                  btn-text="上传文件"
                  @complateSetData="complateSetData($event, 'cover')"
                  @removeFileList="removeFileList($event, 'cover')" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="简介" prop="intro">
          <el-input v-model.trim="helpForm.intro" name="intro" type="textarea" rows="7" placeholder="请输入简介，不超过500字" size="small" maxlength="500" class="width240" show-word-limit />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div class="flex required-box">
            <RichEditor v-model="helpForm.content" :class="{'required-text-editor': blankContent}" class="width240" />
            <p v-if="blankContent" class="required-text-tip">请填写正文内容</p>
          </div>
        </el-form-item>
        <el-form-item label="通知" prop="notifyUsers" class="flex-item">
          <select-custom-user
            v-model="helpForm.vnotifyIds"
            :class="{'red-border': emptyNotifyIds}"
            :max-num="1000"
            :diy-user-item-list.sync="notifyUsersInfo"
            :show-remove-all="true"
            placeholder="请选择通知人"
            dialog-title="选择人员"
            @removeAllUser="removeAllUser"/>
          <div class="checkbox-item">
            <el-checkbox v-model="helpForm.system" :true-label="1" :false-label="0" :style="showMobilePage?'margin-left:0':''" class="system-notify">系统通知</el-checkbox>
            <el-tooltip class="item" placement="top" effect="dark">
              <div slot="content">以系统通知列表中通知指定的人员</div>
              <tipIcon is-diy class="ml5"/>
            </el-tooltip>
          </div>
          <div class="checkbox-item">
            <el-checkbox v-model="helpForm.ding" :true-label="1" :false-label="0">飞书通知</el-checkbox>
            <el-tooltip class="item" placement="top" effect="dark">
              <div slot="content">以飞书上通知的方式通知指定人员</div>
              <tipIcon is-diy class="ml5"/>
            </el-tooltip>
          </div>
          <div class="checkbox-item">
            <el-checkbox v-model="helpForm.isAllNotify">更新通知</el-checkbox>
            <el-tooltip class="item" placement="top" effect="dark">
              <div slot="content">指定时间内以系统弹窗的方式通知所有登录人员一次</div>
              <tipIcon is-diy class="ml5"/>
            </el-tooltip>
          </div>
          <div v-if="helpForm.isAllNotify" class="notify-time-range">
            <div class="label">定时：</div>
            <el-date-picker
              v-model="helpForm.notifyTimeRange"
              :default-time="['00:00:00', '23:59:59']"
              type="datetimerange"
              range-separator="至"
              size="small"
              value-format="timestamp"
              start-placeholder="开始时间"
              end-placeholder="结束时间"/>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="!showMobilePage && (hasRouteAuth('crm:help:edit') || hasRouteAuth('crm:help:add') || isAdmin)" class="crm-add-btn">
      <el-button v-if="btnAuth" :loading="loading" type="primary" plain size="small" class="submit-btn" @click="preview">预览</el-button>
      <el-button v-if="btnAuth" :loading="loading" type="primary" plain size="small" class="submit-btn" @click="toSave('helpForm',false)">快速保存</el-button>
      <el-button v-if="btnAuth" :loading="loading" type="primary" size="small" class="submit-btn" @click="toSave('helpForm',true)">发布</el-button>
      <el-button type="info" size="small" class="cancel-btn-style" @click="toClear">取消</el-button>
    </div>
    <fixed-pagination v-if="showMobilePage">
      <div class="flex-center">
        <MoreOpeator
          :list="[
            { label: '预览', handelClick: preview, auth: btnAuth },
            { label: '快速保存', handelClick: () => {toSave('helpForm',false)}, auth: btnAuth },
            { label: '取消', handelClick: toClear }
        ]">
          <div slot="button" class="btn-left">更多操作<i class="el-icon-arrow-down"/></div>
        </MoreOpeator>
        <el-button v-if="btnAuth" :loading="loading" type="primary" size="small" class="btn-right" @click="toSave('helpForm',true)">发布</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import RichEditor from '@/components/Editor/RichEditor';
import SelectCustomUser from '@/views/legal/process/model/selectCustomUser';
import upAttachment from '@/components/Common/upAttachment/index';
import Title from '@/components/Title';
import { getSideBarData } from '@/components/helpCenter/model/sidebarData';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import { helpInfo, helpAdd, helpEdit } from '@/api/help';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
import { mapState } from 'vuex';
import getParentName from '@/components/helpCenter/mixins/getParentName';
import { showModal } from '@/utils/message';
import { showMsg } from '@/utils/help';

export default {
  components: { Title, RichEditor, SelectCustomUser, upAttachment, MoreOpeator },
  mixins: [getParentName],
  data() {
    return {
      title: '添加文章',
      helpForm: {
        title: '',
        intro: '',
        model: '',
        content: '',
        vnotifyIds: [],
        system: 0,
        ding: 0,
        cover: [],
        isAllNotify: false,
        notifyTimeRange: [],
        notifyStartDate: '',
        notifyEndDate: ''
      },
      notifyUsersInfo: [],
      emptyNotifyIds: false,
      helpRules: {
        title: [{ required: true, trigger: 'blur', message: '请输入标题' }],
        model: [{ required: true, trigger: 'change', message: '请选择模块' }],
        content: [{ required: true, trigger: 'blur', message: '请填写正文内容' }]
      },
      loading: false,
      id: null,
      modelName: '',
      publishMode: '', // 当前的模式，如果是新增文章需要用来控制，如果true则是编辑模式，false则是新增模式，点击快速保存判断依据 值为add和edit
      blankContent: false
    };
  },
  computed: {
    sidebarData() {
      const list = getSideBarData();
      return list;
    },
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    btnAuth() {
      return (this.id ? hasRouteAuth('crm:help:edit') : hasRouteAuth('crm:help:add')) || this.isAdmin;
    }
  },
  watch: {
    'helpForm.content': {
      handler(newVal, oldVal) {
        if (newVal !== '') {
          this.blankContent = false;
        }
      }
    }
  },
  created() {
    this.id = Number(this.$route.params.id) || null;
    this.modelName = this.$route.query.model ? this.getParentName(this.$route.query.model) : 'newRead';
    if (this.modelName) this.helpForm.model = this.modelName;
    if (this.id) {
      this.title = '编辑文章';
      this.getInfo();
    }
  },
  methods: {
    hasRouteAuth,
    getInfo() {
      helpInfo(this.id).then(res => {
        this.notifyUsersInfo = res.data.notifyUsers;
        res.data.vnotifyIds = res.data.notifyUsers.map(item => {
          return item.id;
        });
        if (res.data.notifyStartDate && res.data.notifyEndDate) {
          res.data.notifyTimeRange = [res.data.notifyStartDate, res.data.notifyEndDate];
        }
        this.helpForm = res.data;
      }).catch(err => {
        console.error(err);
      });
    },
    getSelectModelOptions() {
      const aryOptions = [{ name: 'newRead', label: '新手必读' }];
      const sidebarData = this.sidebarData;
      for (let i = 0; i < sidebarData.length; i++) {
        sidebarData[i].children.forEach(item => {
          const obj = {
            name: item.name,
            label: `${sidebarData[i].label}-${item.label}`
          };
          aryOptions.push(obj);
        });
      }
      aryOptions.push({ name: 'announce', label: '公告' });
      return aryOptions;
    },
    toAdd(data, jump) {
      helpAdd(data).then(res => {
        this.loading = false;
        if (res.code === 200 && res.data) {
          this.id = res.data;
          if (jump) {
            ElMessage.success('发布成功');
            this.$router.push({
              name: 'helpDetail',
              params: { id: res.data },
              query: { model: this.helpForm.model }
            });
          } else {
            ElMessage.success('快速保存成功');
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        console.error(err);
        this.loading = false;
      });
    },
    toEdit(data, jump) {
      helpEdit(this.id, data).then(res => {
        this.loading = false;
        if (res.code === 200) {
          if (jump) {
            ElMessage.success('修改成功');
            this.$router.push({
              name: 'helpDetail',
              params: { id: res.data },
              query: { model: this.helpForm.model }
            });
          } else {
            ElMessage.success('快速保存成功');
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        console.error(err);
        this.loading = false;
      });
    },
    toSave(form, jump) { // jump控制保存后需要跳转到新的页面
      if (this.helpForm.content === '<p><br></p>') {
        this.blankContent = true;
        return false;
      }
      this.emptyNotifyIds = false;
      this.$refs[form].validate(valid => {
        if (!valid) {
          return false;
        }
        if (this.helpForm.notifyTimeRange && this.helpForm.notifyTimeRange.length === 2) {
          this.helpForm.notifyStartDate = this.helpForm.notifyTimeRange[0];
          this.helpForm.notifyEndDate = this.helpForm.notifyTimeRange[1];
        }
        this.helpForm.notifyIds = this.helpForm.vnotifyIds.join(',');

        if ((this.helpForm.system || this.helpForm.ding) && this.helpForm.vnotifyIds.length === 0) {
          this.emptyNotifyIds = true;
          return false;
        }
        if (this.helpForm.isAllNotify && (!this.helpForm.notifyStartDate || !this.helpForm.notifyEndDate)) {
          ElMessage.error('请选择通知时间');
          return;
        }
        this.loading = true;
        if (this.id) { // 编辑模式进入
          this.toEdit(this.helpForm, jump);
        } else { // 添加模式进入，第一次点快速保存
          this.toAdd(this.helpForm, jump);
        }
      });
    },
    toClear() {
      this.$router.push({
        name: 'help',
        query: {
          model: this.helpForm.model
        }
      });
    },
    onSave() {
      this.toSave('helpForm', false);
    },
    complateSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.helpForm[key]) {
        this.helpForm[key].push(fileList);
      } else {
        this.$set(this.helpForm, key, [fileList]);
      }
    },
    removeFileList({ file, index }, key) {
      this.helpForm[key].splice(index, 1);
    },
    removeAllUser() {
      showModal('请确认是否删除所有通知人员？', '', {
        center: true,
        showClose: true
      }).then(() => {
        this.notifyUsersInfo = [];
        this.helpForm.vnotifyIds = [];
      });
    },
    preview() {
      showMsg({ title: this.helpForm.title, content: this.helpForm.content }, null, true);
    },
    toHelpList() {
      this.$router.push({ name: 'help', query: { model: 'newRead' }});
    }
  },
  beforeRouteLeave(to, from, next) {
    if (to.name !== 'helpDetail' && this.helpForm.content !== '') {
      // 加定时器是为了解决浏览器后退前进时confirm闪退
      setTimeout(() => {
        this.$confirm('当前文章有内容存在，请确认是否离开当前页面?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          next();
        }).catch(() => {
          next(false);
        });
      }, 200);
    } else {
      next();
    }
  }
};
</script>
<style lang="scss" scoped>
.help-create {
  min-height: calc(100vh - 80px);
  background: #FFFFFF;
  opacity: 1;
  margin: 66px 16px;
  padding: 20px 0;
  .create-head {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 14px;
    margin: 0 76px 0 24px;
    .back {
      color: #999;
      font-size: 16px;
      margin-right: 8px;
      cursor: pointer;
    }
    .el-breadcrumb {
      & ::v-deep {
        .el-breadcrumb__item {
          .el-breadcrumb__inner.is-link {
            font-weight: 400;
            color: #333333;
          }
        }
        .el-breadcrumb__item:last-child .el-breadcrumb__inner{
          font-weight: 400;
          color: #999999;
        }
      }
    }
  }
  .create-box {
    margin: 24px 76px 0 24px;
    .el-form {
      .checkbox-item {
        display: flex;
        align-items: center;
        margin-right: 24px;
      }
      & ::v-deep {
        .el-form-item {
          .el-form-item__content {
            display: flex;
            .el-checkbox__label {
              padding-left: 4px;
            }
            .system-notify{
              margin-left: 17px;
            }
          }
          .red-border {
            position: relative;
            border-color:#F56C6C;
            &::after {
              position: absolute;
              bottom: -25px;
              left: 0;
              content: '请选择通知人';
              font-size: 12px;
              color: #F56C6C;
            }
          }
        }
      }
    }
  }
  .crm-add-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 56px;
    border-top: 1px solid #EBEEFD;
    background: #fff;
    z-index: 10;
    & ::v-deep {
      .el-button {
        height: 32px;
      }
    }
  }
}
.required-text-editor {
  border: 1px solid #F56C6C !important;
}
.required-box {
  flex-direction: column;
  position: relative;
  width: 100%;
}
.required-text-tip {
  position: absolute;
  bottom: -26px;
  margin: 0;
  font-size: 12px;
  color: #F56C6C;
}
.notify-time-range {
  display: flex;
  .label {
    width: 52px;
    color: #606266;
    font-size: 14px;
    line-height: 19px;
    line-height: 32px;
  }
  &::v-deep {
    .el-date-editor {
      width: 360px;
       .el-range-input {
        width: 41%;
      }
      .el-range-separator {
        width: 7%;
      }
    }
  }
}
.mobile-help-create {
  margin: 12px 12px 48px;
  .width240 {
    width: 240px;
  }
}
.mobile-margin {
  margin: 0 12px !important;
}
.flex-item {
  ::v-deep .el-form-item__content{
    display: flex;
    flex-wrap: wrap;
  }
}
.flex-center {
  width: 100%;
  justify-content: space-between;
  .btn-left {
    padding: 4px 25px;
    border: 1px solid #ddd;
    border-radius: 4px;
    color: #666;
    font-size: 14px;
    margin-right: 12px
  }
  .btn-right {
    width: 60%;
  }
}
@media screen and (max-width:1224px) {
  .notify-time-range {
    margin: 12px 0 0;
  }
}
</style>
